package com.stylefeng.guns.modular.yjya.controller;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.entity.vo.TemplateWordConstants;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.common.constant.factory.PageFactory;
import com.stylefeng.guns.common.persistence.dao.PassengerNumMapper;
import com.stylefeng.guns.common.persistence.dao.RoadnetMapper;
import com.stylefeng.guns.common.persistence.model.PassengerNum;
import com.stylefeng.guns.common.persistence.model.Roadnet;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.support.BeanKit;
import com.stylefeng.guns.modular.yjya.dao.PassengerFileDao;
import com.stylefeng.guns.modular.yjya.service.IPassengerNumService;
import com.stylefeng.guns.modular.yjya.transfer.DisposeReport;
import com.stylefeng.guns.modular.yjya.warpper.PassengerFileWarpper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.common.persistence.model.PassengerFile;
import com.stylefeng.guns.modular.yjya.service.IPassengerFileService;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 客流更新控制器
 *
 * @author wsk
 * @Date 2018-09-25 11:12:43
 */
@Controller
@RequestMapping("/passengerFile")
public class PassengerFileController extends BaseController {

    private String PREFIX = "/yjya/passengerFile/";

    @Autowired
    private IPassengerFileService passengerFileService;

    @Autowired
    private PassengerFileDao passengerFileDao;

    @Autowired
    private IPassengerNumService passengerNumService;

    @Autowired
    private PassengerNumMapper passengerNumMapper;

    @Autowired
    private RoadnetMapper roadnetMapper;

    private List<PassengerNum> passengerNumList;

    private String fileNewName;

    /**
     * 跳转到客流更新首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "passengerFile.html";
    }

    /**
     * 跳转到添加客流更新
     */
    @RequestMapping("/passengerFile_add")
    public String passengerFileAdd() {
        return PREFIX + "passengerFile_add.html";
    }

    /**
     * 跳转到修改客流更新
     */
    @RequestMapping("/passengerFile_update/{passengerFileId}")
    public String passengerFileUpdate(@PathVariable Integer passengerFileId, Model model) {
        PassengerFile passengerFile = passengerFileService.selectById(passengerFileId);
        model.addAttribute("dateStatus",passengerFile.getDateStatus().toString());
        model.addAttribute("item",passengerFile);
        LogObjectHolder.me().set(passengerFile);
        return PREFIX + "passengerFile_edit.html";
    }

    /**
     * 获取客流更新列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition) {
        Page<PassengerFile> page = new PageFactory<PassengerFile>().defaultPage();
        List<Map<String, Object>> result = passengerFileDao.getPassengerfiles(page);
        page.setRecords((List<PassengerFile>) new PassengerFileWarpper(result).warp());
        return super.packForBT(page);
    }

    /**
     * 新增客流更新
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(PassengerFile passengerFile) {
        passengerFileService.insert(passengerFile);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除客流更新
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer passengerFileId) {
        passengerFileService.deleteById(passengerFileId);
        return SUCCESS_TIP;
    }

    /**
     * 修改客流更新
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(PassengerFile passengerFile) {
        passengerFile.setPassengerFile(fileNewName);
        passengerNumMapper.deleteByDateStatus(passengerFile.getDateStatus());
        for(int i =0;i<passengerNumList.size();i++){
            passengerNumList.get(i).setDateStatus(passengerFile.getDateStatus());
        }
        passengerNumService.insertBatch(passengerNumList);
        passengerFileService.updateById(passengerFile);
        return super.SUCCESS_TIP;
    }

    /**
     * 客流更新详情
     */
    @RequestMapping(value = "/detail/{passengerFileId}")
    @ResponseBody
    public Object detail(@PathVariable("passengerFileId") Integer passengerFileId) {
        return passengerFileService.selectById(passengerFileId);
    }

    /**
     * 客流文件下载
     * @param id
     * @param request
     * @param response
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/exportExcel/{id}")
    public String exportExcel(@PathVariable("id")Integer id,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
        PassengerFile passengerFile = passengerFileService.selectById(id);
        String fileName = passengerFile.getPassengerFile();
        if (fileName != null) {
            //设置文件路径
            String realPath = "/usr/local/tomcat-7.0.88/webapps/upload/passenger/";
            File file = new File(realPath , fileName);
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                String newFileName = "客流"+ fileName.substring(fileName.lastIndexOf("."));
                response.addHeader("Content-Disposition", "attachment;fileName="+URLEncoder.encode(newFileName,"UTF-8"));// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;

    }

    /**
     * 客流上传
     * @param multipartHttpServletRequest
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(method = RequestMethod.POST,path = "/importExcel")
    @ResponseBody
    public String importExcel(MultipartHttpServletRequest multipartHttpServletRequest, HttpServletResponse response, HttpServletRequest request)throws Exception{
        Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
        for(Map.Entry<String,MultipartFile> entity : fileMap.entrySet()){
            MultipartFile multipartFile = entity.getValue(); //获取上传文件对象
            ImportParams importParams = new ImportParams();
            importParams.setTitleRows(2);
            importParams.setHeadRows(1);
            importParams.setNeedSave(true);
            passengerNumList = ExcelImportUtil.importExcel(multipartFile.getInputStream(),PassengerNum.class,importParams);
            List<Roadnet> roadnetList = roadnetMapper.selectList(null);
            for(int i = 0;i<passengerNumList.size();i++){
                for(int j=0;j<roadnetList.size();j++){

                    if(passengerNumList.get(i).getStartLineName().equals(roadnetList.get(j).getName())){
                        passengerNumList.get(i).setStartLine(roadnetList.get(j).getId());
                    }
                    if(passengerNumList.get(i).getEndLineName().equals(roadnetList.get(j).getName())){
                        passengerNumList.get(i).setEndLine(roadnetList.get(j).getId());
                    }
                    if(passengerNumList.get(i).getStartStationName().equals(roadnetList.get(j).getName())&&roadnetList.get(j).getPid()==passengerNumList.get(i).getStartLine()){
                        passengerNumList.get(i).setStartStation(roadnetList.get(j).getId());
                    }
                    if(passengerNumList.get(i).getEndStationName().equals(roadnetList.get(j).getName())&&roadnetList.get(j).getPid()==passengerNumList.get(i).getEndLine()){
                        passengerNumList.get(i).setEndStation(roadnetList.get(j).getId());
                    }
                }
            }
//            passengerNumService.insertBatch(list);
            if (!multipartFile.isEmpty()) {
                try {
                    SimpleDateFormat format = new SimpleDateFormat("yyyMMddHHmmss");
                    String fileName = multipartFile.getOriginalFilename();
                    fileNewName = format.format(new Date()) + "_" + Math.round(Math.random() * 100000) + fileName.substring(fileName.lastIndexOf("."));
                    // 文件保存路径
                    String filePath = "D:/javatool/tomcat/apache-tomcat-7.0.88-windows-x64/apache-tomcat-7.0.88/webapps/upload/passenger/" + fileNewName;
                    // 转存文件
                    multipartFile.transferTo(new File(filePath));
                    multipartFile.getInputStream().close();
                    return fileNewName;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            multipartFile.getInputStream().close();
        }
        return "文件导入成功";
    }

    /**
     导出Excel模板
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXlsByM", headers = {"Accept=application/vnd.ms-excel"})
    public String exportXlsByT(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        modelMap.put(NormalExcelConstants.FILE_NAME, "客流");
        modelMap.put(NormalExcelConstants.CLASS, PassengerNum.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("客流列表", "导出人:" + ShiroKit.getUser().getName(),
                "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, new ArrayList());
        return NormalExcelConstants.EASYPOI_EXCEL_VIEW;
    }
}
